<template>
    <view class="xilu">
        <view class="page-foot bg-white">
            <view class="flex-box">
                <input type="text" placeholder="说点什么～" @input="bindInput" class="input" placeholder-class="cola" :value="messageText" :focus="inputFocus" />
                <image src="../../static/icon/chat_emoji.png" mode="aspectFill" class="xilu_chatpic" @tap.stop="openEmoji"></image>
                <image src="../../static/icon/chat_pic.png" @click="bindUploadImage()" v-if="!messageText" mode="aspectFill" class="xilu_chatpic"></image>
                <view v-else class="xilu_send" @click="bindSend">发送</view>
            </view>
            <view class="emoji_list" v-if="showEmoji">
                <image :src="v.image" v-for="(v,k) in emotion_json" class="emoji" @tap.stop="chooseEmoji(k)"></image>
            </view>
        </view>
        <view class="xilu_goods_info flex-box bg-white" @click="goDetail()">
            <image :src="product.thumb_image_text" class="xilu_goods_pic" mode="aspectFill"></image>
            <view class="flex-grow-1 pl30">
                <view class="fs30 col10 m-ellipsis">{{product.name}}</view>
                <view class="flex-box pt10">
                    <view class="red fs40 pr20"><text class="fs24">¥</text>{{product.salesprice}}</view>
                    <view class="fs24 col89">{{product.want_num}}人想要</view>
                </view>
                <view class="flex-box flex-col-end flex-between">
                    <view class="fs30 col89">交易前聊一聊</view>
                    <view class="btn1 fs24" v-if="product && product.product_type==1" @click.stop="buy()">立即购买</view>
                </view>
            </view>
        </view>
        <!-- 需配置bottom的偏移量, 用于底部留白 -->
        <mescroll-body ref="mescrollRef" bottom="0%" top="200rpx" @init="mescrollInit" :down="downOption" @down="downCallback" :up="upOption">
            <view @tap.stop="showEmoji = false">
                <!-- 无更多消息 -->
                <view v-if="isEnd" class="msg-end">没有更多消息了</view>
                <block v-for="(item,index) in loadingList.data" :key="msg.id" :id="msg.VIEW_ID">
                    <view class="fs24 cola tc pt30">{{ item.time }}</view>
                    <!-- 消息列表 (必须配置id,以便定位) -->
                    <view class="msg flex-box" v-for="(item2,index2) in item.data" :class="[item2.send_user_id==receive_user_id ? '' : 'flex-row-reserve']">
                        <image :src="item2.send_user_id==receive_user_id?item2.senduser.avatar:item2.senduser.avatar" mode="aspectFill" class="xilu_avatar"></image>

                        <view class="msg-warp" @longpress.native="showMenu(index,index2)" v-if="item2.chat_type==3">商品咨询</view>
                        <view class="msg-warp" @longpress.native="showMenu(index,index2)" v-else-if="item2.chat_type==2">
                            <image :src="item2.content" class="msg-img" mode="widthFix"></image>
                        </view>
                        <block v-else-if="item2.chat_type==1">
                            <view class="msg-warp" @longpress.native="showMenu(index,index2)">
                                <block v-for="v in item2.content">
                                    <image :src="v.value" v-if="v.value.indexOf('https://') != -1" class="emoji"></image>
                                    <text v-if="v.value != '' && v.value.indexOf('https://') == -1">{{v.value}}</text>
                                </block>
                            </view>
                        </block>
                    </view>
                </block>
            </view>
        </mescroll-body>
        <u-action-sheet :actions="list" @select="selectClick" :show="actionSheetShow" cancelText="取消" :closeOnClickOverlay="true" :closeOnClickAction="true" @close="actionSheetShow = false"></u-action-sheet>
    </view>
</template>

<script>
    import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
    const chatIM = require('../../xilu/chat.js');
    export default {
        mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件)
        data() {
            return {
                downOption: {
                    autoShowLoading: true, // 显示下拉刷新的进度条
                    textColor: "#aaa" // 下拉刷新的文本颜色
                },
                upOption: {
                    use: false, // 禁止上拉
                    toTop: {
                        src: '' // 不显示回到顶部按钮
                    }
                },
                refreshSessionStatus: false,
                product: {},
                receive_user_id: 0,
				product_id:0,
                messageText: '',
                pageNum: 1, // 页码
                pageSize: 10, // 页长
                isEnd: false, // 是否无消息
                //msgList: [],
                emotion_json: [], //表情
                loadingList: {
                    total: 0,
                    current_page: 0,
                    last_page: 1,
                    data: []
                },
                showEmoji: false,
                inputFocus: false,
                loadingListIndex:null,
                longpressIndex: null, //长按选中的下标
                list: [{
                    name: '删除'
                }],
                actionSheetShow: false
            };
        },
        onLoad: function(options) {
            var that = this;
            this.getOpenerEventChannel().on('chatProductTransfor', function(data) {
                that.product = data;
                uni.setNavigationBarTitle({
                    title: data.to_username
                })
            })

            // 获取聊天列表
			let userinfo = this.$core.getUserinfo();
            this.receive_user_id = options.receive_user_id || 0;
            this.product_id = options.product_id || 0;
            this.emotion_json = getApp().globalData.chat_config.emoList;
			if(this.receive_user_id == userinfo.id){
				uni.showModal({
					title: '提示',
					content:"自己不可与自己沟通",
					showCancel:false,
					success() {
						uni.navigateBack()
					}
				})
				 return ''
			}
            if (options.product_id && options.product_id > 0) {
                this.product_id = options.product_id;
                chatIM.sendMessage(this.receive_user_id, this.product_id, options.product_id, 3);
            }
        },
        onShow() {
            let page = this;
            uni.$on('msg_list_callback', function(data) {
                //console.log(data, page, 'chat')
                page.msgList(data);
            })
            uni.$on('new_msg_callback', function(data) {
                page.refreshSessionStatus = true;
                page.newMsg(data);
            })
        },
        onUnload: function() {
            uni.$off('new_msg_callback')
            uni.$off('msg_list_callback');
            if (this.refreshSessionStatus) {
                this.getOpenerEventChannel().emit('refreshSession', {});
            }
        },
        onHide: function() {
            uni.$off('new_msg_callback')
            uni.$off('msg_list_callback')
        },
        methods: {
            selectClick(){
                console.log(this.longpressIndex);    
                this.loadingList.data[this.loadingListIndex].data.splice(this.longpressIndex,1);
            },
            // 显示菜单
            showMenu(index,index2) {
                this.loadingListIndex = index;
                this.longpressIndex = index2;
                this.actionSheetShow = true;
            },
            //显示表情
            openEmoji() {
                this.inputFocus = true;
                this.showEmoji = !this.showEmoji;
            },
            //选择表情
            chooseEmoji(k) {
                this.inputFocus = true;
                this.messageText = this.messageText + this.emotion_json[k].name;
            },
            // 输入内容
            bindInput(e) {
                this.messageText = e.detail.value
            },
			//详情
			goDetail(){
				let product = this.product;
				if(product.product_type == 1){
					uni.navigateTo({
						url: '/pages/goods_detail/goods_detail?id='+product.id
					})
				}else{
					uni.navigateTo({
						url: '/pages/recovery_detail/recovery_detail?id='+product.id
					})
				}
			},
            // 点击购买
            buy() {
                uni.navigateTo({
                    url: '/pages/place_order/place_order?product_id=' + this.product.id
                })
            },
            //上传图片
            bindUploadImage() {
                let page = this;
                uni.chooseMedia({
                    count: 9,
                    mediaType: ['image'],
                    sourceType: ['album', 'camera'],
                    maxDuration: 30,
                    camera: 'back',
                    success(res) {
                        for (let i = 0; i < res.tempFiles.length; i++) {
                            // #ifdef MP-WEIXIN
                            page.$core.uploadFile({
                                filePath: res.tempFiles[i].tempFilePath,
                                success: (ret, response) => {
                                    chatIM.sendMessage(page.receive_user_id, page.product_id, ret.data.url, 2);
                                }
                            })
                            // #endif
                            // #ifndef MP-WEIXIN
                            page.$core.uploadFileH5({
                                filePath: res.tempFiles[i].tempFilePath,
                                success: (ret, response) => {
                                    chatIM.sendMessage(page.receive_user_id, page.product_id, ret.data.url, 2);
                                }
                            })
                            // #endif

                        }
                    }
                })
            },
            bindSend() {
                let content = this.messageText;
                if (content.trim() == '') {
                    uni.showToast({
                        title: "发送内容不得为空",
                        icon: 'none'
                    });
                    return false;
                }
                chatIM.sendMessage(this.receive_user_id, this.product_id, content);
                this.messageText = '';
                this.showEmoji = false;
            },
            /*下拉刷新的回调 */
            downCallback() {
                //websocket获取列表
                chatIM.get_msg_list(this.product_id, this.receive_user_id, 1);
            },
            // 获取聊天列表
            msgList(res) {
                var loadingList = res.data;
                // 需自行维护页码
                this.pageNum++;
                // 先隐藏下拉刷新的状态
                this.mescroll.endSuccess();
                // 不满一页,说明已经无更多消息 (建议根据您实际接口返回的总页码数,总消息量,是否有消息的字段来判断)
                if (loadingList.data.length < this.pageSize) {
                    this.isEnd = true; // 标记已无更多消息
                    this.mescroll.lockDownScroll(true); // 锁定下拉
                }
                // 获取当前最顶部的VIEW_ID (注意是写在data.concat前面)
                let topMsg = this.loadingList.data[0]

                if (this.loadingList.current_page > 1) {
                    var now_loadingList_data = this.loadingList.data || [];
                    var now_loadingList_data = now_loadingList_data.concat(loadingList.data);
                    loadingList.data = now_loadingList_data;
                }


                this.loadingList = loadingList;

                this.pageScrollToBottom();

                this.receive_user_id = res.receive_user ? res.receive_user.id : 0;
                chatIM.wsSend({
                    type: 'setread',
                    product_id: this.product_id,
                    receive_user_id: this.receive_user_id
                });
            },

            // 新消息
            newMsg(data) {
                if (data.receive_user_id != this.receive_user_id && data.send_user_id != this.receive_user_id) {
                    return false;
                }
                var loadingList = this.loadingList;
                var now_loadingList_data = loadingList.data || [];
                var ret = chatIM.handle_msg_data(data);
                var now_loadingList_data = now_loadingList_data.concat(ret.data);
                loadingList.data = now_loadingList_data;
                this.loadingList = loadingList;
                this.pageScrollToBottom();
                if (data.send_user_id == this.receive_user_id) {
                    chatIM.wsSend({
                        type: 'setread',
                        product_id: this.product_id,
                        receive_user_id: this.receive_user_id
                    });
                }
            },

            pageScrollToBottom() {
                this.$nextTick(() => {
                    if (this.pageNum <= 2) {
                        // 第一页直接滚动到底部 ( this.pageNum已在前面加1 )
                        this.mescroll.scrollTo(99999, 0)
                    } else if (topMsg) {
                        // 保持顶部消息的位置
                        let view = uni.createSelectorQuery().select('#' + topMsg.VIEW_ID);
                        view.boundingClientRect(v => {
                            console.log("节点离页面顶部的距离=" + v.top);
                            this.mescroll.scrollTo(v.top - 100, 0) // 减去上偏移量100
                        }).exec();
                    }
                })
            }

        }
    }
</script>

<style lang="scss" scoped>
    .page-foot {
        .flex-box {
            padding: 10rpx 30rpx 10rpx 18rpx;
            height: 100rpx;
        }
    }

    .input {
        flex: 1;
        height: 75rpx;
        background: #F7F9FC;
        border-radius: 45rpx;
        padding: 0 22rpx;
        font-size: 30rpx;
        margin-right: auto;
    }

    .xilu {
        background-color: #F7F9FC;

        &_chatpic {
            width: 50rpx;
            height: 50rpx;
            margin-left: 30rpx;
        }

        &_avatar {
            width: 82rpx;
            height: 82rpx;
            border-radius: 50%;
            margin-right: 30rpx;
        }
        .msg-warp{
            .msg-img{
                width: 200rpx;
                display: block;
            }
        }

        .flex-row-reserve {
            .xilu_avatar {
                margin-right: 0;
                margin-left: 30rpx;
            }

            .msg-warp {
                text-align: right;
                background-color: #FFC100;
            }
        }

        &_goods_info {
            padding: 25rpx 30rpx;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 999;

            .btn1 {
                width: 150rpx;
                height: 65rpx;
                line-height: 65rpx;
            }
        }

        &_goods_pic {
            width: 150rpx;
            height: 150rpx;
            border-radius: 10rpx;
        }

        &_send {
            width: 110rpx;
            height: 50rpx;
            line-height: 50rpx;
            background-color: #FFC100;
            border-radius: 50rpx;
            margin-left: 30rpx;
            text-align: center;
            font-size: 24rpx;
        }
    }

    /* 无更多消息 */
    .msg-end {
        padding: 40rpx 0;
        font-size: 24rpx;
        text-align: center;
        color: #aaa;
    }

    /*消息列表*/
    .msg {
        margin: 30rpx;

        &.right {
            text-align: right;
        }

        &.left {
            text-align: left;
        }

        .msg-warp {
            max-width: 460rpx;
            display: inline-block;
            padding: 24rpx 16rpx;
            border-radius: 10rpx;
            background-color: #fff;
            color: #101010;
            font-size: 26rpx;
            text-align: left;
        }
    }

    .emoji {
        width: 64rpx;
        height: 64rpx;
        display: inline-block;
    }

    .emoji_list {
        height: 300rpx;
        overflow-y: scroll;

        .emoji {
            width: 48rpx;
            height: 48rpx;
            margin: 10rpx;
        }
    }



    @supports (bottom: constant(safe-area-inset-bottom)) or (bottom: env(safe-area-inset-bottom)) {
        .msg:last-child {
            margin-bottom: calc(130rpx + 68rpx);
            margin-bottom: calc(constant(safe-area-inset-bottom) + 130rpx);
            margin-bottom: calc(env(safe-area-inset-bottom) + 130rpx);
        }
    }
</style>